package com.example.concurrency.juc.lock.exchanger;

import java.util.concurrent.Exchanger;

public class ExchangerTest {
    public static void main(String[] args) {
        //1. 示例
        example_test_1();
    }

    private static void example_test_1() {
        Exchanger exchanger = new Exchanger();
        for (int i = 0; i < 2; i++) {
            new Thread(new Handler(exchanger,"T-"+i,"OBJ-"+i)).start();
        }
    }

    private static class Handler implements Runnable {
        Exchanger exchanger;
        String name;
        Object object;

        public Handler(Exchanger exchanger, String name, Object object) {
            this.exchanger = exchanger;
            this.name = name;
            this.object = object;
        }

        @Override
        public void run() {
            try {
                Object previous = this.object;
                this.object = this.exchanger.exchange(this.object);
                System.out.println(String.format("name %s exchange %s --> %s ",
                        this.name,
                        previous.toString()
                        , this.object.toString()));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


}